<?php
function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}


function gpspathFunAll($date_offline,$deviceIMEI)
{
		//$path1 = 'http://localhost/gpsapp/data/'.date("d-m-Y", strtotime($date_offline))."/352848025403052.txt";   
	$path1=$GLOBALS[dataPath]."src/data/".date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	
	
	if(chk_folder($path1))
	{
		  $file1 = @fopen($path1, "rb");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			   $data1= fgets($file1);				 
			}
			 $data1 = getSortedData($data1);

			fclose($file1);
		}
		return $data1;
	}
		
}


function getFuel($data,$strtTime,$endTime,$fuel_port){

		if(count($data)>0)
		{ 
		 $data1=explode("#",$data);
		 
		 $j1 = 0;
		 $val= $val1 = $val2 =$val3 =$val4 =$val5=$val6=$val7=$val8=$val9=$val10=$val11=$val12=$val13=$val14=$val15=$val16=$val17=$val18=$val19=$val20=$val21=$val22=$val23 ='1';
		 $c = $c1=$c2=$c3=$c4=$c5=$c6=$c7=$c8=$c9=$c10=$c11=$c12=$c13=$c14=$c15=$c16=$c17=$c18=$c19=$c20=$c21=$c22=$c23='1';
		 
		
		 for($j1=0;$j1<count($data1); $j1++)					
		 { 

				 $data2=explode("@",$data1[$j1]);
				if(count($data2)>1)
				{ 
					$data3=explode(",",$data2[1]);
					  $fule_param = $data3[7]; 
  
					  $d =preg_split("/[\s,]+/",$fule_param);

					  foreach($d as $e){
                          if(substr($e,0,3)=='['.$fuel_port.'='){
                            $v= str_replace(array('['.$fuel_port.'=',']'),'',$e); 
						  }
						  
					  }
					 
					 $calib = $v; 
					
                	/* if(strlen($v)!=2&&$v!='0'){
					  $calib = ($analog_full_tank_signal*$total_tank_size)/($v/1000);
					 } else if($v!='0'){
					  $calib = ($analog_full_tank_signal*$total_tank_size)/$v;
					 }*/

				/*	$vehi=$data3[0];
					$geodate = $data3[8]." ".$data3[9];
					$geoTime = date("h:i",strtotime($data3[9]));
					
					
					$spdTime = $data3[9];
					$altData [$spdTime] = ceil($calib);
                   */
				   
					$spdTime = $data3[9];

                  $t = substr($spdTime,0,2);
				 
				 /* $curTime = explode(":",$data3[9]);
				  $curTime = (($curTime[0]) * 60);
				 if($curTime >= $strtTime && $curTime<=$endTime && $data3[3] > 0)
					{*/
					if(strlen($calib)>2){
				   switch($t){

					   case '00':
                          $val +=ceil($calib);
					   
					       $c +=1;
						  $df[substr($spdTime,0,2)]= ceil($val).','.$c;
						break;
                       case  '01':
						  $val1 +=ceil($calib);
					      $c1 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val1).','.$c1;		
					   break;
                        case '02':
                          $val2 +=ceil($calib);
					      $c2 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val2).','.$c2;		
						break;
					   case '03':
                          $val3 +=ceil($calib);
					      $c3 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val3).','.$c3;		
						break;
                      case '04':
                          $val4 +=ceil($calib);
					      $c4 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val4).','.$c4;		
						
						break;
					  
					  case '05':
                          $val5 +=ceil($calib);
					      $c5 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val5).','.$c5;		
						
					  break;
                      case '06':
                          $val6 +=ceil($calib);
					      $c6 +=1;
						  $df[substr($spdTime,0,2)]= ceil($val6).','.$c6;		
						
					  break;
                    case '07':
                         $val7 +=ceil($calib);
					     $c7 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val7).','.$c7;		
						
					  break;
                    
					  case '08':
                        $val8 +=ceil($calib);
					     $c8 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val8).','.$c8;		
						
					  break;

                    case '09':
                         $val9 +=ceil($calib);
					     $c9 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val9).','.$c9;		
						
					  break;
                  
				  
                    case '10':
                         $val10 +=ceil($calib);
					     $c10 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val10).','.$c10;		
						
					  break;
                  

                  
                    case '11':
                         $val11 +=ceil($calib);
					     $c11 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val11).','.$c11;		
						
					  break;
					  
                    case '12':
                         $val12 +=ceil($calib);
					     $c12 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val12).','.$c12;		
						
					  break;
                  
                    case '13':
                         $val13 +=ceil($calib);
					     $c13 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val13).','.$c13;		
						
					  break;
                  
                    case '14':
                         $val14 +=ceil($calib);
					     $c14 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val14).','.$c14;		
						
					  break;
                  
                    case '15':
                         $val15 +=ceil($calib);
					     $c15 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val15).','.$c15;		
						
					  break;
                  
                    case '16':
                         $val16 +=ceil($calib);
					     $c16 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val16).','.$c16;		
						
					  break;
                  
                    case '17':
                         $val17 +=ceil($calib);
					     $c17 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val17).','.$c17;		
						
					  break;
                  
                    case '18':
                         $val18 +=ceil($calib);
					     $c18 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val18).','.$c18;		
						
					  break;
                  
                    case '19':
                         $val19 +=ceil($calib);
					     $c19 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val19).','.$c19;		
						
					  break;
                  
                    case '20':
                         $val20 +=ceil($calib);
					     $c20 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val20).','.$c20;		
						
					  break;
                  
                    case '21':
                         $val21 +=ceil($calib);
					     $c21 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val21).','.$c21;		
						
					  break;
                  
                    case '22':
                         $val22 +=ceil($calib);
					     $c22 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val22).','.$c22;		
						
					  break;
                  
                    case '23':
                         $val23 +=ceil($calib);
					     $c23 +=1;
						 $df[substr($spdTime,0,2)]= ceil($val23).','.$c23;		
						
					  break;
                  
				   }
				}
				}
			 //}
		}

//		fclose($file1);
		}
		return $df;
 }



if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	


?>
<script type="text/javascript" language="javascript">

function days_between(date1, date2) {

    var ONE_DAY = 1000 * 60 * 60 * 24

    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
	var difference_ms = date1_ms - date2_ms
    return Math.round(difference_ms/ONE_DAY)

}
function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  { alert("Select Vehicle");  document.getElementById('map_device_id').focus();  return 0;  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
	var curdt_array = document.getElementById('curdate').value.split("-");   
	var todt_array = document.getElementById('to_date').value.split("-");
	var frdt_array = document.getElementById('from_date').value.split("-");	
	
	var curdate = new Date(curdt_array[0],(curdt_array[1]-1),curdt_array[2]);
	var todate = new Date(todt_array[0],(todt_array[1]-1), todt_array[2]);
	var frdate = new Date(frdt_array[0],(frdt_array[1]-1), frdt_array[2]);

	var fr_to_diff = days_between(frdate, todate);
	var days_diff = days_between(todate, frdate);

	
	if(fr_to_diff > 0)
	{ alert("From Date should be prior to To Date."); document.getElementById('to_date').select(); return 0;}
	
	return 1;
	
}
function sendCSVData()
{
  document.frmKiloData.submit();
}

function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}
jQuery(function() {

    //$("#time3, #time4").timePicker();
	 $("#time3, #time4").timePicker({
	  startTime: "12:01 AM", // Using string. Can take string or Date object.
	  endTime: "11:59 PM", // Using Date object here.
	  show24Hours: false,
	  separator: ':',
	  step: 1});    
        
    // Store time used by duration.
    var oldTime = $.timePicker("#time3").getTime();
    
    // Keep the duration between the two inputs.
    $("#time3").change(function() {
      if ($("#time4").val()) { // Only update when second input has a value.
        // Calculate duration.
        var duration = ($.timePicker("#time4").getTime() - oldTime);
        var time = $.timePicker("#time3").getTime();
        // Calculate and update the time in the second input.
        $.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
        oldTime = time;
      }
    });
    // Validate.
    $("#time4").change(function() {
      if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
        $(this).addClass("error");
      }
      else {
        $(this).removeClass("error");
      }
    });
    
  });

$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform">
<tr><th colspan="4">Fuel Report</th></tr>
  <tr>
    <td width="15%" align="right"><span class="form_text">Select Device</span></td>
    <td width="35%" align="left" colspan="3">
        <select name="map_device_id" id="map_device_id" class="hours_select" tabindex="1" style="width:50%;" >
        <option value="0">Select Device</option>
        <?php 
        while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
        {
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } ?>	
        </select>
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    </tr>              
    <tr>
    <td width="15%" align="right"><span class="form_text">From Date & Time</span></td>
    <td width="35%" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="2" size="12" value="<?php echo $_POST[from_date]; ?>" style="width:140px;"/>&nbsp;
    <span><input type="text" name="time3" readonly="true" id="time3" size="7" tabindex="3" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="15%" align="right"><span class="form_text">To Date & Time</span></td>
    <td width="35%">
    <input type="text" name="to_date" id="to_date" size="12" style="width:140px;" tabindex="4" readonly="true" value="<?php echo $_POST[to_date]; ?>" />&nbsp;
    <span><input type="text" name="time4" readonly="true" id="time4" size="7" tabindex="5" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
  </tr>

  <tr>
    <td align="right" width="15%"><span class="form_text"></span></td>
    <td align="left" width="35%" colspan="3">
        
        <input type="checkbox" <?php if(isset($_POST[formula]) && $_POST[formula]!=""){echo 'checked';}?> id="formula" name="formula">Use formula
    </td>
    </tr>

  <tr>
    <td height="33" colspan="4" align="center">
    <input type="button" name="map_filter_btn"   value="Filter" class="click_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="click_btn" onclick="location.href='index.php?ch=distance';" tabindex="7" /> 
    </td>
  </tr>
</table>
</form>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	
	

<div style="width:895px; overflow:scroll; overflow-X:hidden;  border:1px solid #dfe9ed; border-top:0px solid #FFF;">

<?php
	
if(isset($_POST[from_date]) && $_POST[to_date]!='')
{ 
	/*echo '<pre>'; print_r($_POST);echo '</pre>';
	exit;*/
	$sdate = $_POST[from_date];
	$edate = $_POST[to_date];
	
	$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
	$strtTime = (($strtTime[0] * 60) + $strtTime[1]);
	
	$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
	$endTime = (($endTime[0] * 60) + $endTime[1]);
	

    $fuel_sql ="select * from tb_fuel where imei=".$_POST[map_device_id]." order by id asc";
	$fuel_rows = $db->query($fuel_sql);
	$k=0;
	 while($fuel_result = @mysql_fetch_assoc($fuel_rows)){
		 $fuel_params[$fuel_result[tanksize]] = $fuel_result[voltage];
		 $k++;
	 }
if(count($fuel_params)>'1'){
 $fuel_values = array_keys($fuel_params);
 $fuel_values_sum = array_sum($fuel_values); 
 $voltage_sum = array_sum($fuel_params);

/*avg voltage and avg fuel values*/
 $a_v = $voltage_sum/$k;
 $a_fuel = $fuel_values_sum/$k;
}


	$fuel_info_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_imeiId =".$_POST[map_device_id]." AND di_status = 1";

		$fuel_info_resp = mysql_query($fuel_info_query);	

		while($fuel_info_fetch = @mysql_fetch_assoc($fuel_info_resp)) {
			
			 $fuel_port = $fuel_info_fetch[di_Fuelport];
			
		}



	//exit;
	if($_POST[from_date] == $_POST[to_date])
	{
		
		 $data =  gpspathFunAll($_POST[from_date],$_POST[map_device_id]);
		
      $s= getFuel($data,$strtTime,$endTime,$fuel_port);
	
		$finData[] = array($_POST[from_date]=>$s);
		/*echo '<pre>';print_r($finData); echo '</pre>';
		exit;*/
	}
	else
	{
		$z = GetDays($sdate, $edate);
		for($y=0; $y<count($z); $y++)
		{ 
			if($y == 0) 
			{
				$strtTime1 = $strtTime;
				$endTime1 = 1439;
				$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);			
				$finData[] = array($z[$y]=>getFuel($data,$strtTime1,$endTime1,$fuel_port));
			}
			elseif($y == count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = $endTime;
				$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);			
				$finData[] = array($z[$y]=>getFuel($data,$strtTime1,$endTime1,$fuel_port));
			}
			elseif($y < count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = 1439;
				$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);			
				$finData[] = array($z[$y]=>getFuel($data,$strtTime1,$endTime1,$fuel_port));
			}
			
			
		}
	}
	
	
	/*$kiloData = "Date,Kilometer";
	$kiloData .= "@";
 echo '<pre>'; print_r($finData);echo '</pre>';
	$z = GetDays($sdate, $edate);
	$cont = 0;*/
	
		

?>	  
<table cellspacing="2" cellpadding="3" border="0" width="100%" class="gridform_final">
      <tbody><tr>
        <th width="30%">Date </th>
        <th width="30%">Time (24 hours format)</th>
        <th width="50%">Fuel (Ltrs)</th>
       </tr>
	  
     
		<?php
	
	/*  foreach($finData as $f=>$t){
		$e = explode(',',$t);
	 $f_v = ceil($e[0]/$e[1]);
		 if(strlen($f_v) >'2'){
		    $calib = ceil(($analog_full_tank_signal*$total_tank_size)/($f_v/1000));
		 } else {
		    $calib = ceil(($analog_full_tank_signal*$total_tank_size)/($f_v));
		 }
	}*/
	for($z='0';$z<count($finData);$z++){
		$sp = $finData[$z];
     foreach($sp as $f=>$s){
		 if(count($s)>1){
		 foreach($s as $key=>$t){
		  $e = explode(',',$t);
	      $f_v = ceil($e[0]/$e[1]);
 
			echo '<tr><td>'.$f.'</td>';
		
		 if(strlen($f_v) >'2'){
			 $v_from_txt = substr(($f_v/1000),0,-2);
          if($_POST[formula]!=""){
			  if($a_v!=""){
			  $calib = ceil(($v_from_txt * $a_fuel)/$a_v);
			  }
		  } else {
			 if(in_array($v_from_txt,$fuel_params)){
				$calib = array_search($v_from_txt,$fuel_params);
			 } else {
				$calib = 'Volatge:'.$v_from_txt.', No matching voltage is provided';

			 }
		  }

			
		 } else {
		    $calib = 'Not a valid voltage';
		 }
		 if(strlen($key)=='1'){
			 $k1 = '0'.($key+1);
		 } else {
             $k1 = $key+1;
		 }
         echo '<td>'.$key .'-'.$k1.'</td>';
		 echo '<td>'.$calib.'</td>';
			 echo '</tr>';

	}
		 }
	 }
	}
	 ?>
</tbody>

</table>	
	<?php }?> 
	
<form name="frmKiloData" id="frmKiloData" method="post" action="../report/export.php">
<input type="hidden" name="txtKiloData" id="txtKiloData" value="<?php echo $kiloData;?>" />
<input type="hidden" name="txtVehino" id="txtVehino" value="<?php echo $_POST[map_device_id]; ?>" />
<input type="hidden" name="txtDate1" id="txtDate1" value="<?php echo $_POST[from_date]; ?>" />
<input type="hidden" name="txtDate2" id="txtDate2" value="<?php echo $_POST[to_date]; ?>" />
</form>	
	
	
</div>	
<script type="text/javascript">

hidePreLoader();
</script>
